﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Diagnostics;
using System.Xml.Linq;
using System.Web;
using TireService.Data;

namespace TireService.Web
{
    public class ScheduledJobs
    {
        public void ExecuteJob(TireServiceDB db, ScheduledJobQueue Job) 
        {
            try
            {
                if (Job.RealisedExecutionTime != null)
                {
                    // Raise error - job has already been run
                    throw new ArgumentException("Job allerede kørt, kan ikke køres igen");
                }

                if ((int)Shared.ScheduledJobId.WebshopOrderInterface == Job.ScheduledJobId)
                {
                    // TODO: Do something
                }

                if ((int)Shared.ScheduledJobId.CustomerServiceReminder == Job.ScheduledJobId)
                {
                    // Send email reminder to all services

                    // Prepare email
                    EmailNotificationServices emailService = new EmailNotificationServices();

                    // Get all services for next coming day
                    List<ServiceCarScheduleDetail> details = db.GetServiceCarScheduleDetails(DateTime.Now.AddDays(1));

                    // Run through all services where task is assigned and customer has confirmed time (and work is not marked as completed)
                    foreach (ServiceCarScheduleDetail detail in details.Where(p => p.TaskId != null & p.CustomerConfirmed == true & p.WorkCompleted == false))
                    {
                        if (detail.ScheduleDetailTypeId == (int)Shared.ScheduleDetailType.ServiceDrive)
                        {
                            bool TireChange = false;

                            // Check if task contains tirechange
                            List<TaskDetail> taskdetails = db.GetTaskDetails(Convert.ToInt32(detail.TaskId));

                            foreach (TaskDetail taskdetail in taskdetails)
                            {
                                if (taskdetail.TaskDetailTypeId == (int)Shared.TaskDetailType.ServiceDrive_ChangeTire)
                                {
                                    TireChange = true;
                                }
                            }

                            if (TireChange)
                            {
                                // Send email reminder

                                Car car = db.GetCar(Convert.ToInt32(detail.CarId));
                                Customer customer = db.GetCustomer(car.CustomerId);

                                // Send reminder email to customer
                                emailService.Customer_ServiceDriveBookingReminder_SendCustomerEmail(customer.CustomerId, customer.Email, car.RegistrationNumber, customer.Name, detail.ScheduleDate.ToShortDateString(), string.Format("{0:t}", detail.StartTime) + " - " + string.Format("{0:t}", detail.EndTime), detail.ToAddress, detail.ToZipCode, detail.ToCity, null);
                            }
                        }
                    }
                }

                if ((int)Shared.ScheduledJobId.BenifyOrderInterface == Job.ScheduledJobId)
                {
                    InterfaceBLL api = new InterfaceBLL();

                    // Get benify partner
                    PartnerListEDI partner = db.GetPartnerEDI(1);

                    // Create xml filename
                    string month = DateTime.Now.Month.ToString();
                    if (month.Length == 1)
                    {
                        month = "0" + month;
                    }

                    string day = DateTime.Now.Day.ToString();
                    if (day.Length == 1)
                    {
                        day = "0" + day;
                    }
                    string XMLfilename = "Mobilhjulskift_" + DateTime.Now.Year.ToString() + month + day + ".xml";
                    string XMLOutputFilename = "Benify_" + DateTime.Now.Year.ToString() + month + day + ".xml";

                    // Copy interface file
                    api.CopyOrderXMLFileFromPartnerSFTP(partner, XMLfilename, XMLOutputFilename);
                }

                if ((int)Shared.ScheduledJobId.TestJob == Job.ScheduledJobId)
                {
                    // Test job - send email to Jannik@mobilhjulskift.dk

                    Shared email = new Shared();
                    email.SendEmail("jannik@mobilhjulskift.dk", "system@mobilhjulskift.dk", "Job virker", "Planlagt job kørt", false, false, null, null, null);
                }

                if ((int)Shared.ScheduledJobId.CreateBenifyOrders == Job.ScheduledJobId)
                {
                    InterfaceBLL api = new InterfaceBLL();

                    // Get benify partner
                    PartnerListEDI partner = db.GetPartnerEDI(1);

                    api.GenerateCustomerAndSubscription(partner.PartnerId, Job.ScheduledExecutionTime);
                }

                // Update job with runtime
                Job.RealisedExecutionTime = DateTime.Now;

                // Check if job should run daily
                if (Job.DailyRepeat)
                {
                    // Create new daily job
                    ScheduledJobQueue newjob = new ScheduledJobQueue();
                    newjob.Title = Job.Title;
                    newjob.ScheduledJobId = Job.ScheduledJobId;
                    newjob.ScheduledExecutionTime = Job.ScheduledExecutionTime.AddDays(1);
                    newjob.DailyRepeat = true;

                    db.AddScheduledJobQueue(newjob);
                }

                // Submit to database
                db.SubmitChanges();
            }
            catch (Exception ex)
            {
                // TODO: Make email notification code to Jannik@mobilhjulskift.dk
            }
        }

    }
}
